package project02.controller.login;

import java.util.logging.Logger;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import org.slim3.controller.validator.Validators;

import project02.dao.UserInfoDao;
import project02.model.UserInfo;

public class AuthenticationController extends Controller {

    @SuppressWarnings("unused")
    private static final Logger logger = Logger.getLogger(AuthenticationController.class.getName());

    private UserInfoDao dao = new UserInfoDao();

    @Override
    public Navigation run() {

        if (!Validate()) {
            return forward("index.jsp");
        }

        UserInfo user = new UserInfo();
        try {
            user = dao.find(asString("userId"));
        } catch (Exception e) {
            return forward("index.jsp");
        }


        if (user == null || !user.getPassword().equals(asString("password"))) {
            return forward("index.jsp");
        }

        sessionScope("userInfo", user);

        String target = sessionScope("target");
        if (target == null || "".equals(target)) {
            return forward("../");
        }
        removeSessionScope("target");
        return forward(target);
    }

    private boolean Validate() {

        Validators val = new Validators(request);
        val.add("userId", val.required());
        val.add("password", val.required());

        return val.validate();
    }
}
